package org.jason.minio.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.minio.starter.template.MinioTemplate;
import io.minio.Result;
import io.minio.messages.Item;
import org.jason.common.exception.ServiceException;
import org.jason.minio.mq.producer.UserProducer;
import org.jason.minio.service.PictureService;
import org.jason.model.common.dtos.ResponseResult;
import org.jason.model.common.enums.HttpCodeEnum;
import org.jason.model.user.dtos.ChangeAvatarDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.regex.Pattern;

@Service
@Transactional
public class PictureServiceImpl implements PictureService {

    @Autowired
    private MinioTemplate minioTemplate;

    @Autowired
    private UserProducer userProducer;


    /**
     * 上传头像
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult uploadAvatar(MultipartFile file) throws Exception {
        int userId = StpUtil.getLoginIdAsInt();
        //判断file是不是图片
        String contentType = file.getContentType();
        if (contentType != null && !contentType.startsWith("image")) {
            return ResponseResult.get(HttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR, "请上传正确的图片文件");
        }
        minioTemplate.putObject("avatar", String.valueOf(userId), file.getInputStream(), -1L, file.getContentType());
        String url = minioTemplate.getObjectURL("avatar", String.valueOf(userId));
        //发送消息到mq
        ChangeAvatarDto dto = new ChangeAvatarDto();
        dto.setUserId(userId);
        dto.setAvatarUrl(url);
        userProducer.sendChangeAvatarQueue(dto);
        return new ResponseResult(HttpCodeEnum.SUCCESS, "获取成功！", url);
    }

    /**
     * 根据id获取用户头像
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult getAvatar(String userId) {
        try {
            String url = minioTemplate.getObjectURL("avatar", userId);
            return new ResponseResult(HttpCodeEnum.SUCCESS, "获取成功！", url);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.get(HttpCodeEnum.DATA_NOT_EXIST, "获取失败！");
        }
    }

    /**
     * 上传素材
     *
     * @param file
     * @return
     */
    @Override
    public ResponseResult uploadMaterial(MultipartFile file) {
        int userId = StpUtil.getLoginIdAsInt();
        //判断file是不是图片
        String contentType = file.getContentType();
        if (contentType != null && !contentType.startsWith("image")) {
            return ResponseResult.get(HttpCodeEnum.PARAM_IMAGE_FORMAT_ERROR, "请上传正确的图片文件");
        }
        try {
            minioTemplate.putObject("material", "/" + userId + "/" + file.getOriginalFilename(), file.getInputStream(), -1L, file.getContentType());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException();
        }
        return ResponseResult.get(HttpCodeEnum.SUCCESS, "上传成功！");
    }

    /**
     * 获取用户上传的素材
     *
     * @return
     */
    @Override
    public ResponseResult getMaterials() {
        int userId = StpUtil.getLoginIdAsInt();
        List<Map<String, String>> list = new ArrayList<>();
        Iterable<Result<Item>> results = minioTemplate.getAllObjectsByPrefix("material", userId + "/", true);
        results.forEach(result -> {
            try {
                //获取文件名
                String objectName = result.get().objectName();
                //根据文件名获取分享路径
                String url = minioTemplate.getObjectURL("material", objectName);
                Map<String, String> map = new HashMap<>();
                map.put("url", url);
                map.put("name", objectName);
                list.add(map);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ServiceException(e.getMessage());
            }
        });
        return new ResponseResult<>(HttpCodeEnum.SUCCESS, list);
    }

    /**
     * 根据文件名删除素材
     *
     * @param filename
     * @return
     */
    @Override
    public ResponseResult deleteMaterial(String filename) {
        if (!Pattern.matches("^[0-9]+/.+\\..+", filename)) {
            return ResponseResult.get(HttpCodeEnum.PARAM_INVALID);
        }
        String userId = StpUtil.getLoginIdAsString();
        //判断filename的开头是否包含userId
        if (!filename.startsWith(userId)) {
            return ResponseResult.get(HttpCodeEnum.NO_OPERATOR_AUTH);
        }
        try {
            minioTemplate.removeObject("material", filename);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
        return ResponseResult.get(HttpCodeEnum.SUCCESS, "删除成功！");
    }
}
